package com.zihan.controller;


import com.zihan.domain.result.Result;
import com.zihan.utils.AliOssUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
public class UploadController {

    @Resource
    private AliOssUtil aliOssUtil;


    @PostMapping("/image")
    public Result<String> uploadImage(MultipartFile file) throws IOException {
        try{
            String originalFilename = file.getOriginalFilename();
            // 获取后缀
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String path = UUID.randomUUID().toString() + suffix;
            String url = aliOssUtil.upload(file.getBytes(), path);
            return Result.success(url);
        }catch (IOException ex) {
            return Result.error("头像上传失败");
        }
    }

    /**
     * 文件上传
     * @return
     */
    @PostMapping("/file")
    public Result<Map<String,String>> uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        String urlPath = aliOssUtil.upload(file.getInputStream(), file.getOriginalFilename());
        // 构建返回结果
        String originalFilename = file.getOriginalFilename();
        String fileType = "";
        if (originalFilename.endsWith(".pdf")) {
            fileType = "pdf";
        }else if (originalFilename.endsWith(".doc") || originalFilename.endsWith(".docx")) {
            fileType = "docx";
        }else if (originalFilename.endsWith(".png") || originalFilename.endsWith(".jpg") || originalFilename.endsWith(".jpeg")) {
            fileType = "image";
        }else if (originalFilename.endsWith(".mp4") || originalFilename.endsWith(".avi")) {
            fileType = "video";
        }else if (originalFilename.endsWith(".zip")) {
            fileType = "zip";
        }
        else if (originalFilename.endsWith(".xlsx")) {
            fileType = "excel";
        }
        HashMap<String, String> res = new HashMap<>();
        res.put("url", urlPath);
        res.put("name", originalFilename);
        res.put("fileType", fileType);
        return Result.success(res);
    }
}
